package com.vic.controller.global;

import com.vic.entity.vo.ResponseVO;;

import com.vic.enums.ResponseCodeEnum;;

import com.vic.exception.BusinessException;;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;



/**
 * @Author: Vic Ly
 */
@RestControllerAdvice
public class GlobalExceptionController extends BaseController{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionController.class);
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request){
        log.error("请求错误，请求地址：{},错误信息：{}",request.getRequestURL(),e);
        ResponseVO responseVO = new ResponseVO();
        if(e instanceof NoHandlerFoundException){
            responseVO.setCode(ResponseCodeEnum.code_404.getCode());
            responseVO.setInfo(ResponseCodeEnum.code_404.getMsg());
            responseVO.setStatus(STATUS_ERROR);
        }else if(e instanceof BusinessException){
            // 业务错误
            BusinessException b = (BusinessException) e;
            responseVO.setCode(b.getCode());
            responseVO.setInfo(b.getMessage());
            responseVO.setStatus(STATUS_ERROR);
        }else if(e instanceof BindException){
            // 参数类型错误
            responseVO.setCode(ResponseCodeEnum.code_600.getCode());
            responseVO.setInfo(ResponseCodeEnum.code_600.getMsg());
            responseVO.setStatus(STATUS_ERROR);
        }else if(e instanceof DuplicateKeyException){
            // 主键冲突
            responseVO.setCode(ResponseCodeEnum.code_601.getCode());
            responseVO.setInfo(ResponseCodeEnum.code_601.getMsg());
            responseVO.setStatus(STATUS_ERROR);
        }else{
            responseVO.setCode(ResponseCodeEnum.code_500.getCode());
            responseVO.setInfo(ResponseCodeEnum.code_500.getMsg());
            responseVO.setStatus(STATUS_ERROR);
        }
        return responseVO;
    }
}
